int factorial( int N ) { if ( N == 0 ) return 1; else return N * factorial( N-1 ); }
If you have a correct math-like definition of what you want to do, then transforming it into a Java method is almost mechanical.
But, you can also think about what happens as the method runs. This is a dynamic view of recursion. The diagram shows the how the activation chain grows as the method executes.
Each activation except the base case requires another activation.
This is because the statement return n * factorial( N-1 )
factorial( N-1 )
int factorial( int N ) { if ( N == 0 ) return 1; else return N * factorial( N-1 ) ; }
When the base case is reached, return values start being passed up the chain. After an activation has returned a value to its caller it is no longer active. The diagram shows this as a dotted circle.
(Practice Dynamic Thinking: ) What would happen if
factorial()